package com.example.kaogong.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.kaogong.common.utils.RespBean;
import com.example.kaogong.sys.mapper.*;
import com.example.kaogong.sys.pojo.*;
import com.example.kaogong.sys.pojo.dto.CourseAddDto;
import com.example.kaogong.sys.pojo.vo.CourseDetailInfoVo;
import com.example.kaogong.sys.pojo.vo.CourseInfoVo;
import com.example.kaogong.sys.pojo.vo.CourseResourceVo;
import com.example.kaogong.sys.pojo.vo.CourseVideoVo;
import com.example.kaogong.sys.service.ICourseResourceService;
import com.example.kaogong.sys.service.ICourseService;
import com.example.kaogong.sys.service.ICourseTagService;
import com.example.kaogong.sys.service.ICourseVideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author    
 * @since 2022-03-26
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    @Autowired
    private TeacherMapper teacherMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private CourseTagMapper courseTagMapper;

    @Autowired
    private ICourseTagService courseTagService;

    @Autowired
    private FavoriteMapper favoriteMapper;

    @Autowired
    private ICourseVideoService courseVideoService;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private ICourseResourceService courseResourceService;

    @Value("${qiniu.url}")
    private String urlHead;


    /**
     * 当前登录教师新增课程
     * @param name
     * @param courseAddDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RespBean addCourse(String name, CourseAddDto courseAddDto) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", name));
        if (null == user || user.getRoleId() != 2)
            return RespBean.error("权限不足");
        Teacher teacher = teacherMapper.selectOne(new QueryWrapper<Teacher>().eq("uid", user.getUid()));
        if (null == teacher)
            return RespBean.error();

        Course course = new Course();
        course.setCourseImg("course-img/default.jpg");
        course.setCourseExplain(courseAddDto.getCourseExplain());
        course.setCourseMark(courseAddDto.getCourseMark());
        course.setCourseName(courseAddDto.getCourseName());
        course.setCourseFeature(courseAddDto.getCourseFeature());
        course.setTeacherId(teacher.getTeacherId());
        course.setTypeId(courseAddDto.getTypeId());

        int insert = courseMapper.insert(course);
        if (insert < 1)
            return RespBean.error();

        List<CourseTag> courseTagList = new ArrayList<>();
        Course insertCourse = courseMapper.selectOne(new QueryWrapper<Course>().eq("course_name", courseAddDto.getCourseName()));
        for (Integer tag : courseAddDto.getCourseTags()) {
            CourseTag courseTag = new CourseTag();
            courseTag.setCourseId(insertCourse.getCourseId());
            courseTag.setTagId(tag);
            courseTagList.add(courseTag);
        }
        boolean saveBatch = courseTagService.saveBatch(courseTagList);
        if (!saveBatch) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return RespBean.error();
        }
        return RespBean.success();
    }

    /**
     * 根据课程编号逻辑删除课程
     * @param courseId
     * @return
     */
    @Override
    public RespBean deleteCourseByCourseId(Integer courseId) {
        int delete = courseMapper.deleteCourseByCourseId(courseId);
        if (delete < 1)
            return RespBean.error();
        return RespBean.success();
    }

    /**
     * 根据课程编号修改课程缩略图
     * @param courseId
     * @param fileName
     * @return
     */
    @Override
    public RespBean updateCourseImg(Integer courseId, String fileName) {
        int update = courseMapper.updateCourseImg(courseId, fileName);
        if (update < 1)
            return RespBean.error();
        return RespBean.success();
    }

    /**
     * 根据课程编号修改课程基本信息
     * @param course
     * @param courseId
     * @return
     */
    @Override
    public RespBean updateCourseInfo(Course course, Integer courseId) {
        int update = courseMapper.update(course, new UpdateWrapper<Course>().eq("course_id", courseId));
        if (update < 1)
            return RespBean.error();
        return RespBean.success();
    }


    /**
     * 根据课程编号获取课程详细信息
     * @param courseId
     * @return
     */
    @Override
    public RespBean<CourseDetailInfoVo> getCourseDetailInfoByCourseId(Integer courseId) {
        // 查询基本信息
        CourseDetailInfoVo courseDetailInfoVo = courseMapper.getCourseDetailInfoByCourseId(courseId);

        // 课程缩略图url
        courseDetailInfoVo.setCourseImg(urlHead + courseDetailInfoVo.getCourseImg());

        // 课程标签
        List<String> courseTags = courseTagMapper.getCourseTagByCourseId(courseId);
        courseDetailInfoVo.setCourseTags(courseTags);

        // 收藏数
        Integer count = favoriteMapper.selectCount(new QueryWrapper<Favorite>().eq("course_id", courseId));
        courseDetailInfoVo.setFavorite(count);

        // 课程视频列表
        List<CourseVideoVo> courseVideoVoList = courseVideoService.getCourseVideoListByCourseId(courseId);
        courseDetailInfoVo.setCourseVideoVoList(courseVideoVoList);

        // 课程资料列表
        List<CourseResourceVo> courseResourceVoList = courseResourceService.getCourseResourceListByCourseId(courseId);
        courseDetailInfoVo.setCourseResourceVoList(courseResourceVoList);
        return RespBean.success(courseDetailInfoVo);
    }

    @Override
    public RespBean<Page<CourseInfoVo>> getCourseInfo(Long current, Long size, String name) {
        Integer teacherId = null;
        if (null != name) {
            User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", name));
            if (null == user || user.getRoleId() != 2)
                return RespBean.error();
            teacherId = teacherMapper.selectOne(new QueryWrapper<Teacher>().eq("uid", user.getUid())).getTeacherId();
        }
        Page<CourseInfoVo> courseInfoVoPage = courseMapper.getCourseInfo(new Page<CourseInfoVo>(current, size), teacherId);
        courseInfoVoPage.getRecords().forEach(courseInfoVo -> {
            //收藏数
            Integer count = favoriteMapper.selectCount(new QueryWrapper<Favorite>().eq("course_id", courseInfoVo.getCourseId()));
            courseInfoVo.setFavorite(count);
            // url
            courseInfoVo.setCourseImg(urlHead + courseInfoVo.getCourseImg());
            // 课程标签
            List<String> courseTags = courseTagMapper.getCourseTagByCourseId(courseInfoVo.getCourseId());
            courseInfoVo.setCourseTags(courseTags);
        });
        return RespBean.success(courseInfoVoPage);
    }

    /**
     * 当前登录学生收藏课程
     * @param courseId
     * @param name
     * @return
     */
    @Override
    public RespBean favoriteCourse(Integer courseId, String name) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", name));
        if (null == user || user.getRoleId() != 3)
            return RespBean.error();
        Student student = studentMapper.selectOne(new QueryWrapper<Student>().eq("uid", user.getUid()));
        Favorite favorite = new Favorite();
        favorite.setCourseId(courseId);
        favorite.setSid(student.getSid());
        int insert = favoriteMapper.insert(favorite);
        if (insert < 1)
            return RespBean.error();
        return RespBean.success();
    }

    @Override
    public RespBean<CourseInfoVo> getCourseInfoById(Integer courseId) {
        CourseInfoVo courseInfoVo = courseMapper.getCourseInfoById(courseId);
        courseInfoVo.setCourseImg(urlHead + courseInfoVo.getCourseImg());
        //收藏数
        Integer count = favoriteMapper.selectCount(new QueryWrapper<Favorite>().eq("course_id", courseInfoVo.getCourseId()));
        courseInfoVo.setFavorite(count);
        // 课程标签
        List<String> courseTags = courseTagMapper.getCourseTagByCourseId(courseInfoVo.getCourseId());
        courseInfoVo.setCourseTags(courseTags);
        return RespBean.success(courseInfoVo);
    }
}
